var express = require('express');
var router = express.Router();
const {
    Article,
    Cate,
    Comment,
    User
} = require('../models')

// 新闻详情: 新闻的数据和此新闻对应的评论信息
router.get('/articles/:id', async function(req, res) {
    const id = req.params.id - 0
    const articles = await Article.findAll({
        attributes: ['id', 'title', 'content', 'add_time', 'view_nums', 'author', 'cate_id'],
        where: {
            id
        }
    })

    if (articles.length > 0) {
        return res.cc(200, {
            code: 200,
            msg: '查询成功',
            data: articles
        })
    } else {
        return res.cc(400, {
            code: 400,
            msg: '暂无数据'
        })
    }
})

// 查询某条新闻的评论数据
router.get('/comments/:articleId', async function(req, res) {
    const comments = await Comment.findAll({
        attributes: ['id', 'content', 'add_time', 'userId'],
        where: {
            articleId: req.params.articleId
        },
        order: [
            ['add_time', 'desc']
        ],
        include: [{
            model: User,
            attributes: ['username']
        }]
    })
    if (comments && comments.length) {
        return res.cc(200, {
            code: 200,
            msg: '查询成功',
            data: comments
        })
    } else {
        return res.cc(400, {
            code: 400,
            msg: '暂无数据'
        })
    }

})

// 查询某个分类下对应的新闻数据
router.get('/cates/:id', async function(req, res) {
    const page = req.query.page - 0 || 1
    const limit = req.query.limit - 0 || 5
    const data = await Article.findAll({
        attributes: ['id', 'title', 'add_time', 'cate_id', 'picture'],
        where: {
            is_del: 1,
            cate_id: req.params.id
        },
        include: [{
            model: Cate,
            attributes: ['cate_name']
        }],
        order: [
            ['view_nums', 'desc']
        ],
        offset: (page - 1) * limit,
        limit
    })
    if (data.length > 0) {
        return res.cc(200, {
            code: 200,
            msg: '查询成功',
            data
        })
    } else {
        return res.cc(400, {
            code: 400,
            msg: '暂无数据'
        })
    }
})

// 更新新闻的访问量
router.put('/articles/updateView/:id', async function(req, res) {
    const id = req.params.id
    await Article.increment({
        view_nums: 1
    }, {
        where: {
            id
        }
    })
    res.cc(200)
})




module.exports = router;